package com.szewec.ps.ui.road.facilities.intersection.task;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;

import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;

import com.alibaba.fastjson.JSON;
import com.szewec.ps.R;
import com.szewec.ps.base.BaseActivity;
import com.szewec.ps.base.BaseMediaPickerActivity;
import com.szewec.ps.base.Constants;
import com.szewec.ps.base.FileUpload;
import com.szewec.ps.databinding.ActivityCenterDividerBinding;
import com.szewec.ps.model.PresentValue;
import com.szewec.ps.model.response.ResponseData;
import com.szewec.ps.myinterface.BindEditTextViewValue;
import com.szewec.ps.myview.toast.bamtoast.BamToast;
import com.szewec.ps.ui.road.facilities.intersection.task.enums.RoadEnums;
import com.szewec.ps.ui.road.facilities.intersection.task.model.CenterDivider;
import com.szewec.ps.ui.road.facilities.intersection.task.utils.BeanUtils;
import com.szewec.ps.ui.road.facilities.intersection.task.utils.ViewUtils;
import com.szewec.ps.util.CommonUtils;
import com.szewec.ps.util.RollUtil;
import com.szewec.ps.util.StringUtils;
import com.szewec.ps.util.TextViewUtil;
import com.szewec.ps.util.imagepicker.adapter.CustomPickerAdapterShowAndEdit;
import com.szewec.ps.util.imagepicker.data.MediaFile;
import com.szewec.ps.util.okhttp.OkHttp;

import org.apache.commons.collections4.CollectionUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.ButterKnife;

public class CenterDividerActivity extends BaseMediaPickerActivity implements BindEditTextViewValue {

    private ActivityCenterDividerBinding binding;

    private String flag;

    //接收到的数据
    private CenterDivider centerDivider = new CenterDivider();
    //用来上传的数据
    private CenterDivider newCenterDivider = new CenterDivider();
    //分隔带形式
    private List<String> dividerShapeList = new ArrayList<>();
    //掉头口
    private List<String> turnAroundList = new ArrayList<>();

    // 照片上传数组
    private List<String> photoSketchUploadIdArr = new ArrayList<>();
    // 照片文件数组
    private ArrayList<MediaFile> photoSketchFileArr = new ArrayList<>();
    // 图片适配器
    private CustomPickerAdapterShowAndEdit photoSketchAdapter;
    // 移除的图片ID数组
    private List<String> deletePhotoIdArr = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_center_divider);
        ButterKnife.bind(this);
        Bundle presentValue = getIntent().getExtras();
        PresentValue<CenterDivider> value = (PresentValue<CenterDivider>) presentValue.getSerializable(Constants.EXTRA_KEY.ENTRANCE_ROAD);
        flag = value.getFlag();
        centerDivider = value.getT();

        initTitleBar();
        initSelect();
        initViewFile();
        if (flag.equals(Constants.PRESENT_VALUE_FLAG.EDIT)) {
            setInputData();
        }
    }

    private void initTitleBar() {
        binding.titleBar.setLeftLayoutVisibility(View.VISIBLE);
        binding.titleBar.setLeftLayoutClickListener(v -> {
            saveData();
            CommonUtils.showIsSave(CenterDividerActivity.this, this::upTo);
        });
        binding.titleBar.setRightLayoutVisibility(View.VISIBLE);
        binding.titleBar.setRightTextVisibility(View.VISIBLE);
        binding.titleBar.setRightTextClickListener(v -> {
            saveData();
            if (BeanUtils.comparisonOutside(this.centerDivider, newCenterDivider)) {
                BamToast.showText(this, Constants.ErrorMsg.NOT_UPDATE, false);
                return;
            }
            upTo();
        });
    }

    private void initSelect() {
        dividerShapeList = Arrays.asList(getResources().getStringArray(R.array.center_divider));
        turnAroundList = Arrays.asList(getResources().getStringArray(R.array.turn_around));

        binding.itDividerShape.setSelectTypeClickListener(v -> {
            TextViewUtil.closeKeyboard(this);
            RollUtil.alertBottomWheelOption(this, dividerShapeList, binding.itDividerShape.getSelectTextView(), (view, index) ->
                    binding.itDividerShape.setValue(dividerShapeList.get(index)));
        });
        binding.itTurnAround.setSelectTypeClickListener(v -> {
            TextViewUtil.closeKeyboard(this);
            RollUtil.alertBottomWheelOption(this, turnAroundList, binding.itTurnAround.getSelectTextView(), (view, index) ->
                    binding.itTurnAround.setValue(turnAroundList.get(index)));
        });

        // 初始化照片适配器
        photoSketchAdapter = initTypeMediaRecyclerView(photoSketchUploadIdArr, photoSketchFileArr,
                binding.photoSketchSketchRV, true, false, true, deletePhotoIdArr);
    }

    private void setInputData() {
        BeanUtils.stripTrailingZeros(centerDivider);
        binding.itDividerShape.setValue(RoadEnums.CenterDivider.getValueByKey(centerDivider.getDividerShape()));

        binding.itDividerWidth.setValue(centerDivider.getDividerWidth());
        binding.itTurnAround.setValue(RoadEnums.TurnAround.getValueByKey(centerDivider.getTurnAround()));
        binding.ckSafetyIsland.setChecked(centerDivider.getSafetyIsland());
    }

    // 设置照片
    private void initViewFile() {
        // 先根据fileId查询附件数据
        if (!CollectionUtils.isEmpty(centerDivider.getAddIds())) {
            requestFilesByIds(centerDivider.getAddIds(), this::initAdapterData);
        }
        // 根据业务ID查询附件信息
        else if (StringUtils.isNotEmpty(centerDivider.getId())) {
            requestFiles(FileUpload.RoadInvestigationFileBizTypeEnum.ROAD_CENTER_DIVIDER_FILE_BIZ_TYPE, centerDivider.getId(), this::initAdapterData);
        }
    }

    // 往照片适配器里面设置图片显示
    private void initAdapterData(List<MediaFile> mediaFileList) {
        if (CollectionUtils.isEmpty(mediaFileList)) {
            return;
        }
        photoSketchUploadIdArr.clear();
        photoSketchFileArr.clear();
        // 添加到文件数组
        photoSketchFileArr.addAll(mediaFileList);
        for (MediaFile mediaFile : photoSketchFileArr) {
            photoSketchUploadIdArr.add(mediaFile.getId());
        }
        // 设置适配器数据源
        photoSketchAdapter.setmMediaFileList(mediaFileList);
    }

    /**
     * 导流走新增还是修改
     */
    private void upTo() {
        if (newCenterDivider.getDividerWidth() == null) {
            BamToast.showText(this, R.string.requires_text_filed_check, false);
            return;
        }

        if (flag.equals(Constants.PRESENT_VALUE_FLAG.ADD)) {
            postData();
        } else if (flag.equals(Constants.PRESENT_VALUE_FLAG.EDIT)) {
            putData();
        }
    }

    //保存数据到对象
    private void saveData() {
        BeanUtils.copyObj(this.centerDivider, this.newCenterDivider);

        newCenterDivider.setAddIds(photoSketchUploadIdArr);
        newCenterDivider.setRemoveIds(deletePhotoIdArr);
        newCenterDivider.setDividerShape(RoadEnums.CenterDivider.getKeyByValue(binding.itDividerShape.getStringValue()));
        newCenterDivider.setDividerWidth(binding.itDividerWidth.getBigDecimalValue());
        newCenterDivider.setTurnAround(RoadEnums.TurnAround.getKeyByValue(binding.itTurnAround.getStringValue()));
        newCenterDivider.setSafetyIsland(binding.ckSafetyIsland.getChecked());
    }

    /**
     * 存入后台
     */
    private void postData() {
        OkHttp.post("/tpms-plan-service/api/center-divider/", newCenterDivider, result -> {
            ResponseData responseData = JSON.parseObject(result, ResponseData.class);
            if (responseData.getCode() == Constants.ResponseCode.SUCCESS) {
                newCenterDivider = JSON.parseObject(responseData.getData().toString(), CenterDivider.class);
                BamToast.showText(this, responseData.getMsg(), true);
                Intent intent = new Intent();
                intent.putExtra(Constants.EXTRA_KEY.ENTRANCE_ROAD, this.newCenterDivider);
                setResult(Constants.RESULT_CODE.NEED_REFRESH, intent);
                finish();
            } else {
                BamToast.showText(this, responseData.getMsg(), false);
            }
        });
    }

    //修改数据存入后台
    private void putData() {
        OkHttp.put("/tpms-plan-service/api/center-divider/", newCenterDivider, result -> {
            ResponseData responseData = JSON.parseObject(result, ResponseData.class);
            if (responseData.getCode() == Constants.ResponseCode.SUCCESS) {
                BamToast.showText(this, responseData.getMsg(), true);
                setResult(Constants.RESULT_CODE.NEED_REFRESH);
                finish();
            } else {
                BamToast.showText(this, responseData.getMsg(), false);
            }
        });
    }

    @Override
    public void setObjValue() {

    }

    @Override
    public boolean checkLinkedDataAndFiles() {
        return !BeanUtils.comparisonOutside(this.centerDivider, newCenterDivider);
    }

    //监听滑动
    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (ViewUtils.isClickNotInView(v, event)) {//点击editText控件外部
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    TextViewUtil.closeKeyboard(this);
                    v.clearFocus();
                }
            }
            return super.dispatchTouchEvent(event);
        }
        // 必不可少，否则所有的组件都不会有TouchEvent了
        return getWindow().superDispatchTouchEvent(event) || onTouchEvent(event);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK) {
            //拍照返回，或者视频录制返回
            if (isAdapterImagePickerResult(requestCode, photoSketchAdapter)) {
                ArrayList<MediaFile> mediaFileList = getMediaFileListWhenOnActivityResult(requestCode, data, photoSketchAdapter);
                saveFileAndRefreshAdapter(mediaFileList, photoSketchUploadIdArr, photoSketchAdapter,
                        FileUpload.RoadInvestigationFileBizTypeEnum.ROAD_CENTER_DIVIDER_FILE_BIZ_TYPE);
            }
        }
    }
}